package com.springapp.mvc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.springapp.mvc.dao.bean.Location;
import com.springapp.mvc.params.LocationMonitorParam;
import com.springapp.mvc.params.LocationQueryParam;
import com.springapp.mvc.resultBean.*;
import com.springapp.mvc.service.Interface.LocationService;
import com.springapp.mvc.service.Interface.OperationService;
import com.springapp.mvc.util.HttpClient;
import com.springapp.mvc.util.JsonUtils;
import com.springapp.mvc.websocket.SocketMessageBean;
import com.springapp.mvc.websocket.WebSocketService;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 6/20/2018.
 */

@Controller
@RequestMapping("/location")
public class LocationCollectionController
{
    @Autowired(required = false)
    LocationService mLocationService;
    @Autowired(required = false)
    OperationService mOperationService;

    private static final String GAODE_KEY = "95c4a3513eb5fc2db2a91ca905530b2e";

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "monitor")
    public BaseResult receiveLocationInfo(@RequestBody LocationMonitorParam param)
    {
        BaseResult result = new BaseResult();
        if(param == null)
        {
            result.setResult(ResultCode.INVAIDPARAM);
            return result;
        }
        String address = "";
        Map<String,String> regeoParams = new HashMap<String,String>();
        regeoParams.put("key",GAODE_KEY);
        regeoParams.put("location",param.getLon()+","+param.getLat());
        String regeoRet = HttpClient.get("https://restapi.amap.com/v3/geocode/regeo",regeoParams);
        try
        {
            GaoDeRegeoResult regeoResult = JsonUtils.decode(regeoRet,GaoDeRegeoResult.class);
            address = regeoResult.getRegeocode().getFormatted_address();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        long locationId = mLocationService.insertCurrentLocation((float) param.getLon(), (float) param.getLat(), address);
        result.setResult(ResultCode.SUCCESS);

        // 命令更新成已上传
        mOperationService.changeOperationStatus(param.getOperationId(), true);

        // 通知管理平台一条operation已经被执行,且一条位置已经上传
        SocketMessageBean sockBean = new SocketMessageBean();
        sockBean.setType("1");
        sockBean.setData(mOperationService.queryOperationById(param.getOperationId()));

        SocketMessageBean sockBean2 = new SocketMessageBean();
        sockBean2.setType("2");
        sockBean2.setData(mLocationService.queryLocationById(locationId));
        try {
            WebSocketService.sendObjectToAll(sockBean);
            WebSocketService.sendObjectToAll(sockBean2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET,value = "delete")
    public BaseResult deleteLocation(int id)
    {
        BaseResult result = new BaseResult();
        int ret = mLocationService.deleteLocation(id);
        result.setCode("0");
        return result;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "query")
    public BaseResult queryLocation(LocationQueryParam param)
    {
        if(param == null)
            return null;
        BaseResult result = new BaseResult();
        CommonDatatableBean tableBean = new CommonDatatableBean();
        tableBean.setDraw(0);
        int totalAmount = mLocationService.getLocationCount();
        tableBean.setRecordsTotal(totalAmount);
        tableBean.setRecordsFiltered(totalAmount);
        int limit = param.getStart();
        List<Object> list = new ArrayList<Object>();
        String sortType = param.getSortType() == 0?"ASC":"DESC";
        List<Location> locations = mLocationService.queryLocationPaged(limit, param.getOffset(), param.getSortPro(), sortType);
        if(locations != null && locations.size() > 0)
        {
            for(Location location:locations)
            {
                list.add(location);
            }
        }
        tableBean.setData(list);
        result.setData(tableBean);
        result.setResult(ResultCode.SUCCESS);
        return result;
    }
}
